<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="盘点单号">
          <el-input
            v-model="queryParams.stockcheckCode"
            placeholder="请输入盘点单号"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="openadd()"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            @click="handleDeleteBatch"
            :disabled="!selectedRowIds.length"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download">导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain>作废</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain @click="getcang">锁定仓库</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="Refresh" @click="fetchData"
            >刷新</el-button
          >
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        v-loading="isLoading"
        @selection-change="handleSelectionChange"
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="stockcheckCode" label="盘点单号" width="150" />
        <el-table-column prop="processor" label="盘点人" width="100" />
        <el-table-column prop="stockNum" label="盘点数量" width="100" />
        <el-table-column prop="preparer" label="制单人" width="100" />
        <el-table-column prop="department" label="部门" width="100" />
        <el-table-column prop="formcreationTime" label="制单时间" width="160">
          <template #default="{ row }">{{
            formatTime(row.formcreationTime)
          }}</template>
        </el-table-column>

        <el-table-column prop="stockcheckType" label="盘点类型" width="100" />
        <el-table-column prop="startTime" label="盘点开始时间" width="160">
          <template #default="{ row }">{{
            formatTime(row.startTime)
          }}</template>
        </el-table-column>
        <el-table-column prop="endTime" label="盘点结束时间" width="160">
          <template #default="{ row }">{{ formatTime(row.endTime) }}</template>
        </el-table-column>
        <el-table-column prop="outboundState" label="出库状态" width="100">
          <template #default="scope">
            <span v-if="scope.row.outboundState == 1">未出库</span>
            <span v-else-if="scope.row.outboundState == 2">部分出库</span>
            <span v-else-if="scope.row.outboundState == 3">已出库</span>
          </template>
        </el-table-column>
        <el-table-column prop="inboundState" label="入库状态" width="100">
          <template #default="scope">
            <span v-if="scope.row.inboundState == 1">未入库</span>
            <span v-else-if="scope.row.inboundState == 2">部分入库</span>
            <span v-else-if="scope.row.inboundState == 3">已入库</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click="openFormDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        style="margin-top: 20px"
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageSizeChange"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 新增对话框 -->
    <el-dialog
      title="新增盘点"
      v-model="dialogVisible"
      width="70%"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="addForm"
        :rules="rules"
        label-width="100px"
      >
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>基础信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="盘点单号" prop="stockcheckCode">
                <el-input
                  v-model="addForm.stockcheckCode"
                  placeholder="自动获取系统编号"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="盘点类型" prop="stockcheckType">
                <el-select
                  v-model="addForm.stockcheckType"
                  placeholder="请选择盘点类型"
                  style="width: 100%"
                >
                  <el-option label="全部盘点" value="全部盘点" />
                  <el-option label="部分盘点" value="部分盘点" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库状态" prop="inboundState">
                <el-select
                  v-model="addForm.inboundState"
                  placeholder="请选择入库状态"
                  style="width: 100%"
                >
                  <el-option label="未入库" :value="1" />
                  <el-option label="部分入库" :value="2" />
                  <el-option label="已入库" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出库状态" prop="outboundState">
                <el-select
                  v-model="addForm.outboundState"
                  placeholder="请选择出库状态"
                  style="width: 100%"
                >
                  <el-option label="未出库" :value="1" />
                  <el-option label="部分出库" :value="2" />
                  <el-option label="已出库" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="盘点开始时间" prop="startTime">
                <el-date-picker
                  v-model="addForm.startTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="盘点结束时间" prop="endTime">
                <el-date-picker
                  v-model="addForm.endTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仓库名称" prop="warehouseId">
                <el-select
                  v-model="addForm.warehouseId"
                  placeholder="请选择仓库"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in warehouseList"
                    :key="item.id"
                    :label="item.warehouseName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门" prop="outboundState">
                <el-select
                  v-model="addForm.department"
                  placeholder="请选择部门"
                  style="width: 100%"
                >
                  <el-option label="人事部" value="人事部" />
                  <el-option label="宣传部" value="宣传部" />
                  <el-option label="销售部" value="销售部" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经办人" prop="processor">
                <el-input
                  v-model="addForm.processor"
                  placeholder="请输入经办人"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="制单人" prop="preparer">
                <el-input
                  v-model="addForm.preparer"
                  placeholder="请输入制单人"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="制单时间" prop="formcreationTime">
                <el-date-picker
                  v-model="addForm.formcreationTime"
                  type="datetime"
                  placeholder="选择制单时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card shadow="never" style="margin-top: 20px">
          <template #header>
            <div class="card-header">
              <span>盘点明细</span>
            </div>
          </template>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="addDetailRow"
                >添加</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="Delete"
                @click="removeDetailRows"
                :disabled="!selectedDetails.length"
                >移除</el-button
              >
            </el-col>
          </el-row>

          <el-alert
            v-if="!addForm.desc.length"
            title="请添加货品！"
            type="info"
            show-icon
            :closable="false"
            style="margin-bottom: 10px"
          />

          <el-table
            :data="addForm.desc"
            @selection-change="handleDetailSelectionChange"
            show-summary
            :summary-method="getSummaries"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column label="货品名称" width="180">
              <template #default="scope">
                <el-select
                  v-model="scope.row.goodsId"
                  placeholder="选择货品"
                  @change="(val:any) => handleProductChange(val, scope.row)"
                >
                  <el-option
                    v-for="p in productList"
                    :key="p.id"
                    :label="p.goodsName"
                    :value="p.id"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="goodsId" label="货品编号" width="120" />
            <el-table-column prop="goodsNum" label="库存数量" width="120" />

            <el-table-column label="盘点数量" width="150">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.stockNum"
                  :min="0"
                  controls-position="right"
                  style="width: 100%"
                  @change="(val:any) => handleCheckQtyChange(val, scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="chaStockNum" label="盈亏数量" width="100" />
            <el-table-column label="盘点状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.statusType">{{
                  scope.row.statusText
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  @click="removeDetailRow(scope.$index)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose(false)">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      title="修改盘点"
      v-model="updatedialogVisible"
      width="70%"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="updateData"
        :rules="rules"
        label-width="100px"
      >
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>基础信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="盘点单号" prop="stockcheckCode">
                <el-input
                  v-model="updateData.stockcheckCode"
                  placeholder="自动获取系统编号"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="盘点类型" prop="stockcheckType">
                <el-select
                  v-model="updateData.stockcheckType"
                  placeholder="请选择盘点类型"
                  style="width: 100%"
                >
                  <el-option label="全部盘点" value="全部盘点" />
                  <el-option label="部分盘点" value="部分盘点" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库状态" prop="inboundState">
                <el-select
                  v-model="updateData.inboundState"
                  placeholder="请选择入库状态"
                  style="width: 100%"
                >
                  <el-option label="未入库" :value="1" />
                  <el-option label="部分入库" :value="2" />
                  <el-option label="已入库" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出库状态" prop="outboundState">
                <el-select
                  v-model="updateData.outboundState"
                  placeholder="请选择出库状态"
                  style="width: 100%"
                >
                  <el-option label="未出库" :value="1" />
                  <el-option label="部分出库" :value="2" />
                  <el-option label="已出库" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="盘点开始时间" prop="startTime">
                <el-date-picker
                  v-model="updateData.startTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="盘点结束时间" prop="endTime">
                <el-date-picker
                  v-model="updateData.endTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仓库名称" prop="warehouseId">
                <el-select
                  v-model="updateData.warehouseId"
                  placeholder="请选择仓库"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in warehouseList"
                    :key="item.id"
                    :label="item.warehouseName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门" prop="outboundState">
                <el-select
                  v-model="updateData.department"
                  placeholder="请选择部门"
                  style="width: 100%"
                >
                  <el-option label="人事部" value="人事部" />
                  <el-option label="宣传部" value="宣传部" />
                  <el-option label="销售部" value="销售部" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经办人" prop="processor">
                <el-input
                  v-model="updateData.processor"
                  placeholder="请输入经办人"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="制单人" prop="preparer">
                <el-input
                  v-model="updateData.preparer"
                  placeholder="请输入制单人"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="制单时间" prop="formcreationTime">
                <el-date-picker
                  v-model="updateData.formcreationTime"
                  type="datetime"
                  placeholder="选择制单时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card shadow="never" style="margin-top: 20px">
          <template #header>
            <div class="card-header">
              <span>盘点明细</span>
            </div>
          </template>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="updateDetailRow"
                >添加</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
            type="danger"
            plain
            icon="Delete"
            @click="updateremoveDetailRows"
            :disabled="!updateSelectedDetails.length"
            >移除</el-button
          >
            </el-col>
          </el-row>

          <el-alert
            v-if="!updateData.desc"
            title="请添加货品！"
            type="info"
            show-icon
            :closable="false"
            style="margin-bottom: 10px"
          />

          <el-table
            :data="updateData.desc"
            @selection-change="updatehandleDetailSelectionChange"
            show-summary
            :summary-method="getSummaries"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column label="货品名称" width="180">
              <template #default="scope">
                <el-select
                  v-model="scope.row.goodsId"
                  placeholder="选择货品"
                  @change="(val:any) => handleProductChange(val, scope.row)"
                >
                  <el-option
                    v-for="p in productList"
                    :key="p.id"
                    :label="p.goodsName"
                    :value="p.id"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="goodsId" label="货品编号" width="120" />
            <el-table-column prop="goodsNum" label="库存数量" width="120" />

            <el-table-column label="盘点数量" width="150">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.stockNum"
                  :min="0"
                  controls-position="right"
                  style="width: 100%"
                  @change="(val:any) => handleCheckQtyChange(val, scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="chaStockNum" label="盈亏数量" width="100" />
            <el-table-column label="盘点状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.statusType">{{
                  scope.row.statusText
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  @click="updateremoveDetailRow(scope.$index)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose(false)">取 消</el-button>
          <el-button type="primary" @click="updatehandleSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { nextTick } from 'vue';
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import moment from "moment";
import axios from "axios";
import { useRouter } from "vue-router";
const router=useRouter();
// 定义接口返回的盘点列表项类型
interface StockCheckItem {
  id: number;
  stockcheckCode: string;
  stockcheckType: string;
  startTime: string;
  endTime: string;
  // 模拟字段以匹配UI
  outboundState: string;
  inboundState: string;
  processor: string;
  stockNum: number;
  preparer: string;
  department: string;
  formcreationTime: string;
}

// 定义仓库列表项类型
interface WarehouseItem {
  id: number;
  warehouseName: string;
}

const queryParams = reactive({
  stockcheckCode: "",
  result: "",
  type: "",
  warehouseId: "",
});

const tableData = ref<StockCheckItem[]>([]);
const warehouseList = ref<WarehouseItem[]>([]);
const isLoading = ref(false);
const selectedRowIds = ref<number[]>([]);

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 子组件弹窗状态
const dialogVisible = ref(false);
const isEdit = ref(false);
const currentItemId = ref<number | null>(null);

const formRef = ref();

// 新增/编辑表单
const addForm = reactive({
  stockcheckCode: "",
  stockcheckType: "",
  startTime: "",
  endTime: "",
  outboundState: 0,
  inboundState: 0,
  processor: "",
  preparer: "",
  warehouseId: "",
  desc: [
    {
      id: 0,
      stockId: "",
      goodsId: "",
      goodsNum: 0,
      stockNum: 0,
      chaStockNum: 0,
      remark: "",
    },
  ],
  department: "",
  formcreationTime: "",
});

// 表单验证规则
const rules = reactive({
  stockcheckType: [
    { required: true, message: "盘点类型不能为空", trigger: "change" },
  ],
  startTime: [
    { required: true, message: "盘点开始时间不能为空", trigger: "change" },
  ],
  endTime: [
    { required: true, message: "盘点结束时间不能为空", trigger: "change" },
  ],
});

// 盘点明细相关
const productList = ref<any[]>([]); // 货品列表
const selectedDetails = ref<any[]>([]); // 新增对话框明细中选中的行
const updateSelectedDetails = ref<any[]>([]); // 修改对话框明细中选中的行

// 模拟的出入库状态
const outStatus = ["未出库", "部分出库", "已出库"];
const inStatus = ["未入库", "部分入库", "已入库"];
const results = ["有盈亏", "无盈亏", "草稿"];

// 获取盘点列表数据
const fetchData = async () => {
  isLoading.value = true;
  try {
    const response = await axios.get(
      "http://localhost:5198/api/StockTaking/GetStockTaking",
      {
        params: {
          ...queryParams,
          page: pagination.currentPage,
          pageSize: pagination.pageSize,
        },
      }
    );
    if (response.data && response.data.data) {
      tableData.value = response.data.data.map((item: any) => ({
        ...item,
        result: results[Math.floor(Math.random() * results.length)],
        warehouseName: "货品仓库一",
        outboundState: outStatus[Math.floor(Math.random() * outStatus.length)],
        inboundState: inStatus[Math.floor(Math.random() * inStatus.length)],
        products: "三锅头、可笑、何必等8项...",
        stockNum: 50,
        profitNum: 50,
      }));
      pagination.total = response.data.total || response.data.data.length;
    }
  } catch (error) {
    console.error("获取盘点列表失败:", error);
    ElMessage.error("获取盘点列表失败");
  } finally {
    isLoading.value = false;
  }
};

// 获取仓库列表
const fetchWarehouseList = async () => {
  try {
    const res = await axios.get(
      "http://localhost:5198/api/Warehouse/GetWarehouse"
    );
    if (res.data && res.data.data) {
      warehouseList.value = res.data.data;
    }
  } catch (error) {
    console.error("获取仓库列表失败:", error);
    ElMessage.error("获取仓库列表失败");
  }
};

// 查询
const handleQuery = () => {
  pagination.currentPage = 1;
  fetchData();
};

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    stockcheckCode: "",
    result: "",
    type: "",
    warehouseId: "",
  });
  handleQuery();
};

// 打开新增/编辑弹窗
const openadd = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");

  addForm.stockcheckCode = `${year}${month}${day}${hours}${minutes}${seconds}`;
  dialogVisible.value = true;
  fetchProductList();
};
// 生成入库单号：当前时间的年月日时分秒格式

// 获取货品列表用于下拉选择

// 提交表单
const handleSubmit = async () => {
  axios
    .post("http://localhost:5230/api/StockTaking/AddStockTaking", addForm)
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        dialogVisible.value = false;
      } else {
        ElMessage.error(res.data.msg);
      }
    });
};

// 单条删除
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm("确定要删除这条盘点记录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await axios.put(
      "http://localhost:5230/api/StockTaking/DelStockTaking",
      { id: id }
    );
    ElMessage.success("删除成功");
    fetchData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 批量删除
const handleDeleteBatch = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRowIds.value.length} 条记录吗?`,
      "提示",
      { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
    );
    await axios.put(
      "http://localhost:5230/api/StockTaking/DeleteStockTakingBatch",
      { data: { ids: selectedRowIds.value } }
    );
    ElMessage.success("批量删除成功");
    fetchData();
    selectedRowIds.value = [];
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除失败:", error);
      ElMessage.error("批量删除失败");
    }
  }
};

// 表格选择项变化
const handleSelectionChange = (selection: StockCheckItem[]) => {
  selectedRowIds.value = selection.map((item) => item.id);
};

// 分页大小变化
const handlePageSizeChange = (size: number) => {
  pagination.pageSize = size;
  fetchData();
};

// 当前页变化
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchData();
};

// 子组件保存成功后的回调
const handleDialogClose = (refresh: boolean) => {
  dialogVisible.value = false;
  if (refresh) {
    fetchData();
  }
};

// 重置表单
const resetForm = () => {
  addForm.stockcheckCode = "";
  addForm.stockcheckType = "存货盘点";
  addForm.startTime = "";
  addForm.endTime = "";
  addForm.department = "";
  addForm.processor = "";
  addForm.formcreationTime = "";
  addForm.desc = [];
  addForm.inboundState = 0;
  addForm.outboundState = 0;
  addForm.preparer = "";

  formRef.value?.resetFields();
};

// 获取货品列表（模拟）
const fetchProductList = () => {
  // 实际应从API获取
  return axios.get("http://localhost:5198/api/StockTaking/GetGoods").then((res) => {
    productList.value = res.data.data;
    return res.data.data;
  });
};

// 添加明细行
const addDetailRow = () => {
  addForm.desc.push({
    id: 0,
    stockId: "",
    goodsId: "",
    goodsNum: 0,
    stockNum: 0,
    chaStockNum: 0,
    remark: "",
  });
};

// 移除选中的明细行
const removeDetailRows = () => {
  selectedDetails.value.forEach((row) => {
    const index = addForm.desc.indexOf(row);
    if (index !== -1) {
      addForm.desc.splice(index, 1);
    }
  });
  selectedDetails.value = [];
};

// 移除单条明细行
const removeDetailRow = (index: number) => {
  addForm.desc.splice(index, 1);
};

// 明细行选择变化
const handleDetailSelectionChange = (selection: any[]) => {
  selectedDetails.value = selection;
};

// 选择货品后联动
const handleProductChange = (goodsId: number, row: any) => {
  const product = productList.value.find((p) => p.id === goodsId);
  if (product) {
    row.stockId = product.stockId;
    row.goodsNum = product.goodsNum;
    row.stockNum = product.stockNum;
    row.remark = product.remark;
    updateProfitLoss(row);
  }
};

// 修改盘点数量后联动
const handleCheckQtyChange = (value: number, row: any) => {
  updateProfitLoss(row);
};

// 更新盈亏数量和状态
const updateProfitLoss = (row: any) => {
  row.chaStockNum = row.stockNum - row.goodsNum;
  if (row.chaStockNum > 0) {
    row.statusText = "盘盈";
    row.statusType = "success";
  } else if (row.chaStockNum < 0) {
    row.statusText = "盘亏";
    row.statusType = "danger";
  } else {
    row.statusText = "正常";
    row.statusType = "info";
  }
};

// 表格合计
const getSummaries = (param: any) => {
  const { columns, data } = param;
  const sums: any[] = [];
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (
      ["bookQuantity", "checkQuantity", "profitLossQuantity"].includes(
        column.property
      )
    ) {
      const values = data.map((item: any) => Number(item[column.property]));
      if (!values.every((value: any) => isNaN(value))) {
        sums[index] = values.reduce((prev: any, curr: any) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
      } else {
        sums[index] = "";
      }
    }
  });
  return sums;
};

// 格式化时间
const formatTime = (time: string | null | undefined): string => {
  return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : "-";
};

// 初始化
onMounted(() => {
  fetchData();
  fetchWarehouseList();
});

const updatedialogVisible = ref(false);
const updateData = reactive({
  id: 0,
  stockcheckCode: "",
  stockcheckType: "",
  startTime: "",
  endTime: "",
  outboundState: 0,
  inboundState: 0,
  processor: "",
  preparer: "",
  warehouseId: 1,
  desc: [
    {
      id: 0,
      stockId: "",
      goodsId: 0,
      goodsNum: 0,
      stockNum: 0,
      chaStockNum: 0,
      remark: "",
    },
  ],
  department: "人事部",
  formcreationTime: "",
  DelName: "",
  CreateName: "",
  UpdateName: "",
  Desc: []
});
const openFormDialog = (row: any) => {
    // 保存状态值，确保是有效的选项值(1,2,3)，默认为1
    const outboundStateValue = Number(row.outboundState) || 1;
  const inboundStateValue = Number(row.inboundState) || 1;
 
  const parseDate = (dateStr: any): string => {
    const date = new Date(dateStr);
    return isNaN(date.getTime()) ? "" : date.toString();
  };
    // 设置所有基础信息
    updateData.department = updateData.department;
    updateData.id = row.id;
    updateData.stockcheckCode = row.stockcheckCode;
    updateData.stockcheckType = row.stockcheckType;
    updateData.startTime = row.startTime ? parseDate(row.startTime) : '';
    updateData.endTime = row.endTime ? parseDate(row.endTime) : '';
    updateData.processor = row.processor;
    updateData.preparer = row.preparer;
    updateData.warehouseId = 1;
    updateData.formcreationTime = row.formcreationTime ? parseDate(row.formcreationTime) : '';
    
    // 设置状态字段为有效值
    updateData.outboundState = outboundStateValue;
    updateData.inboundState = inboundStateValue;

    // 确保货品数据加载完成后再设置明细
    fetchProductList().then(() => {
      // 处理盘点明细数据并初始化状态
      if (Array.isArray(row.desc) && row.desc.length > 0) {
        updateData.desc = row.desc.map(item => {
          // 计算并设置盈亏状态
          const chaStockNum = Number(item.stockNum) - Number(item.goodsNum);
          let statusText = '正常';
          let statusType = 'info';
          
          if (chaStockNum > 0) {
            statusText = '盘盈';
            statusType = 'success';
          } else if (chaStockNum < 0) {
            statusText = '盘亏';
            statusType = 'danger';
          }
          
          // 确保 goodsId 是数字类型以匹配下拉框
          const goodsId = Number(item.goodsId);
          // 检查货品是否存在于产品列表中
          const productExists = productList.value.some(p => p.id === goodsId);
          
          return {
            ...item,
            chaStockNum,
            statusText,
            statusType,
            goodsId: productExists ? goodsId : 0, // 如果不存在则设为0
            stockNum: Number(item.stockNum),
            goodsNum: Number(item.goodsNum)
          };
        });
      } else {
        updateData.desc = [{
          id: 0,
          stockId: "",
          goodsId: 0,
          goodsNum: 0,
          stockNum: 0,
          chaStockNum: 0,
          remark: "",
          statusText: '正常',
          statusType: 'info'
        }];
      }

      // 打开对话框
      updatedialogVisible.value = true;

      // 确保对话框渲染完成后重新设置状态字段
      setTimeout(() => {
        updateData.outboundState = outboundStateValue;
        updateData.inboundState = inboundStateValue;
      }, 300);
    });
  };
const updatehandleSubmit = async () => {
  // 创建一个新的请求对象，确保所有必填字段都有值
  const requestData = {
    ...updateData,
    DelName: updateData.DelName || updateData.processor || "system",
    CreateName: updateData.CreateName || updateData.processor || "system",
    UpdateName: updateData.UpdateName || updateData.processor || "system",
    Desc: updateData.desc.length > 0 ? updateData.desc : [{ id: 0 }], // 确保Desc不为空数组
    stockcheckCode: updateData.stockcheckCode || `CHECK-${Date.now()}`,
    stockcheckType: updateData.stockcheckType || "存货盘点",
    department: updateData.department || "默认部门",
    preparer: updateData.preparer || "system",
    processor: updateData.processor || "system"
  };

  // 打印请求数据以便调试
  console.log("提交的数据:", requestData);

  axios
    .put("http://localhost:5230/api/StockTaking/UpdateStockTaking", requestData)
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        updatedialogVisible.value = false;
        fetchData(); // 更新数据列表
      } else {
        ElMessage.error(res.data.msg);
      }
    });
};
// 添加明细行
const updateDetailRow = () => {
  updateData.desc.push({
    id: 0,
    stockId: "",
    goodsId: 0,
    goodsNum: 0,
    stockNum: 0,
    chaStockNum: 0,
    remark: "",
  });
};

// 移除修改对话框中选中的明细行
const updateremoveDetailRows = () => {
  updateSelectedDetails.value.forEach((row) => {
    const index = updateData.desc.indexOf(row);
    if (index !== -1) {
      updateData.desc.splice(index, 1);
    }
  });
  updateSelectedDetails.value = [];
};

// 移除单条明细行
const updateremoveDetailRow = (index: number) => {
  updateData.desc.splice(index, 1);
};

// 修改对话框明细行选择变化
const updatehandleDetailSelectionChange = (selection: any[]) => {
  updateSelectedDetails.value = selection;
};
const getcang=()=>{
    router.push('/warehouse');
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
</style>
